package com.chuanyun.wechatcheckin.service;

import com.chuanyun.wechatcheckin.config.WechatConfig;
import com.chuanyun.wechatcheckin.model.wechat.VacationQuotaResponse;
import com.chuanyun.wechatcheckin.model.wechat.WechatTokenResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信假期服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VacationService {
    
    private final WechatConfig wechatConfig;
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 获取假期应用访问令牌（使用打卡应用Secret）
     * @return 访问令牌 
     * @throws Exception
     */
    public String getVacationAccessToken() throws Exception {
        String url = wechatConfig.getApi().getBaseUrl() + wechatConfig.getApi().getTokenUrl() +
                "?corpid=" + wechatConfig.getCorpId() +
                "&corpsecret=" + wechatConfig.getCheckinSecret();
        
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            
            return httpClient.execute(httpGet, response -> {
                String responseBody = EntityUtils.toString(response.getEntity());
                
                WechatTokenResponse tokenResponse = objectMapper.readValue(responseBody, WechatTokenResponse.class);
                
                if (tokenResponse.isSuccess()) {
                    return tokenResponse.getAccessToken();
                } else {
                    log.error("获取企业微信假期应用访问令牌失败: {}", tokenResponse.getErrMsg());
                    throw new RuntimeException("获取假期应用访问令牌失败: " + tokenResponse.getErrMsg());
                }
            });
        }
    }
    
    /**
     * 获取成员假期余额
     * @param userId 成员userid
     * @return 假期余额响应
     * @throws Exception
     */
    public VacationQuotaResponse getUserVacationQuota(String userId) throws Exception {
        String accessToken = getVacationAccessToken();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/vacation/getuservacationquota?access_token=" + accessToken;
        
        // 构建请求参数
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("userid", userId);
        
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
            
            String jsonBody = objectMapper.writeValueAsString(requestBody);
            httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
            
            return httpClient.execute(httpPost, response -> {
                String responseBody = EntityUtils.toString(response.getEntity());
                log.info("获取成员假期余额响应: {}", responseBody);
                
                VacationQuotaResponse vacationResponse = objectMapper.readValue(responseBody, VacationQuotaResponse.class);
                
                if (!vacationResponse.isSuccess()) {
                    log.error("获取成员假期余额失败: userId={}, errcode={}, errmsg={}", 
                            userId, vacationResponse.getErrcode(), vacationResponse.getErrmsg());
                }
                
                return vacationResponse;
            });
        }
    }
    
    /**
     * 将秒转换为天数
     * @param seconds 秒数
     * @return 天数
     */
    public static double secondsToDays(long seconds) {
        return seconds / 86400.0;
    }
    
    /**
     * 将秒转换为小时数
     * @param seconds 秒数
     * @return 小时数
     */
    public static double secondsToHours(long seconds) {
        return seconds / 3600.0;
    }
}